package com.cloudcc.boot.web;

import com.cloudcc.boot.core.CCObject;
import com.cloudcc.boot.core.CCService;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static com.cloudcc.boot.core.CCService.userInfo;

@Service
@Slf4j
public class OA_Operate {
    @Value("${system.localurl:''}")
    public String fileUrl ;
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    private static Map<String, Map<String, String>> dictMap = Maps.newHashMap();

    static {
        Map<String, String> jklx = Maps.newHashMap();//合同 主表：价款类型
        jklx.put("总价", "0");
        jklx.put("订单合同", "9");
        jklx.put("框架合同", "7");
        jklx.put("非总价", "1");
        jklx.put("无价款", "2");
        jklx.put("补充协议", "8");
        dictMap.put("jklx", jklx);

        Map<String, String> jsfs = Maps.newHashMap();//合同 主表：结算方式
        jsfs.put("电汇", "0");
        jsfs.put("银行承兑", "1");
        jsfs.put("商业承兑", "2");
        jsfs.put("其他", "3");
        dictMap.put("jsfs", jsfs);

        Map<String, String> xmsfylx = Maps.newHashMap();//项目立项 主表：是否预立项
        xmsfylx.put("是", "0");
        xmsfylx.put("否", "1");
        dictMap.put("xmsfylx", xmsfylx);

        Map<String, String> sfhtt = Maps.newHashMap();//项目立项/项目预立项 主表：是否含塔筒
        sfhtt.put("是", "0");
        sfhtt.put("否", "1");
        dictMap.put("sfhtt", sfhtt);

        Map<String, String> bqzl = Maps.newHashMap();//投标文件评审/招标文件评审 主表：标前资料
        bqzl.put("已上报齐全", "0");
        bqzl.put("未上报齐全", "1");
        dictMap.put("bqzl", bqzl);
    }

    /**
     * 获取记录字段值（通用）
     */
    public String getRecordValue(String objectApiName, String recordID,String recordApi) {
        CCService cs = new CCService(userInfo);
        String recordValue = "";
        List<CCObject> mainObj = cs.cquery(objectApiName, "id='" + recordID + "'");//主表
        if (CollectionUtils.isNotEmpty(mainObj)) {
            CCObject recordObj = mainObj.get(0);
            recordValue = recordObj.get(recordApi) == null ? "" : recordObj.get(recordApi).toString();
        }
        return recordValue;
    }

    /**
     * 获取记录类型名称
     */
    public String getType(String objectApiName, String recordID) {
        CCService cs = new CCService(userInfo);
        String recordtypeName = "";
        List<CCObject> mainObj = cs.cquery(objectApiName, "id='" + recordID + "'");//主表
        if (CollectionUtils.isNotEmpty(mainObj)) {
            CCObject recordObj = mainObj.get(0);
            String recordtype = recordObj.get("recordtype") == null ? "" : recordObj.get("recordtype").toString();//记录类型id
            String tmp = " select r.recordname from recordtype r where r.id = '"+recordtype+"'";
            List<CCObject> rel_cqlQuery = cs.cqlQuery("recordtype", tmp);
            if (CollectionUtils.isNotEmpty(rel_cqlQuery)) {
                CCObject recordtypeObj = rel_cqlQuery.get(0);
                recordtypeName = recordtypeObj.get("recordname") == null ? "" : recordtypeObj.get("recordname").toString();//
            }
        }
        return recordtypeName;
    }

    /**
     * 获取OA用户ID
     */
    public String getOaUserId(String objectApiName, String recordID, String oa_user_type) {
        CCService cs = new CCService(userInfo);
        String oa_user_id = "";
        List<CCObject> mainObj = cs.cquery(objectApiName, "id='" + recordID + "'");//主表
        if (CollectionUtils.isNotEmpty(mainObj)) {
            CCObject recordObj = mainObj.get(0);
            String ownerid = recordObj.get("ownerid") == null ? "" : recordObj.get("ownerid").toString();//所有人
            List<CCObject> userList = cs.cquery("ccuser", "id='" + ownerid + "'");
            if (userList.size() > 0) {
                CCObject userObj = userList.get(0);
                String loginname = userObj.get("loginname") == null ? "" : userObj.get("loginname").toString();//用户名（员工编号）
                List<CCObject> oauserList = cs.cquery("oayg", "ygbh like'" + loginname + "%' and accounttype='"+oa_user_type+"'");//OA员工
                if (oauserList.size() > 0) {
                    CCObject oauserObj = oauserList.get(0);
                    oa_user_id = oauserObj.get("oaid") == null ? "" : oauserObj.get("oaid").toString();//人员ID
                }
            }
        }
        return oa_user_id;
    }

    /**
     * 获取CRM所有人姓名
     */
    public String getCRMOwner(String objectApiName, String recordID) {
        CCService cs = new CCService(userInfo);
        String owneridccname = "";
        List<CCObject> mainObj = cs.cquery(objectApiName, "id='" + recordID + "'");//主表
        if (CollectionUtils.isNotEmpty(mainObj)) {
            CCObject recordObj = mainObj.get(0);
            owneridccname = recordObj.get("owneridccname") == null ? "" : recordObj.get("owneridccname").toString();//所有人
        }
        return owneridccname;
    }

    /**
     * 获取主数据list
     */
    public List<CCObject> getMainList(String objectApiName, String recordID) {
        CCService cs = new CCService(userInfo);
        List<CCObject> mainObj = cs.cquery(objectApiName, "id='" + recordID + "'");//主表
        return mainObj;
    }

    /**
     * 主表映射(CRM-->OA)
     *
     * @param objectApiName crm对象api
     * @param recordID      crm主表记录id
     * @param modelName     oa映射表模块名称
     * @return
     */
    public List<JSONObject> dealOAMainParam(String objectApiName, String recordID, String modelName, String oa_user_type) {

        CCService cs = new CCService(userInfo);
        List<CCObject> mainObj = cs.cquery(objectApiName, "id='" + recordID + "'");//主表
        if (CollectionUtils.isEmpty(mainObj)) {
            log.info("无数据mainObj，后续无需处理");
            return null;
        }
        log.info("mainObj:{}====={}", mainObj.size(), mainObj);
        List<CCObject> oamappingObj = cs.cquery("oafieldmapping", "name='" + modelName + "'");//OA字段映射;
        if (CollectionUtils.isEmpty(oamappingObj)) {
            log.info("无数据oamappingObj，后续无需处理");
            return null;
        }
        log.info("================");
        log.info("oamappingObj:=={}==={}", oamappingObj.size(), oamappingObj);
        Map<String, CCObject> fieldMap = Maps.newHashMap();
        oamappingObj.forEach(d -> {
            String key = d.get("crmapi") == null ? "" : d.get("crmapi").toString();
            if (StringUtils.isBlank(key)) {
                return;
            }
            fieldMap.put(key, d);
        });
        List<JSONObject> list = Lists.newArrayList();
        CCObject object = mainObj.get(0);
        object.forEach((k, v) -> {
            //k 字段名-->fieldMap.key v 字段值
            CCObject fieldObj = fieldMap.get(k);
            if (fieldObj == null) {
                return;
            }
            String oaapi = fieldObj.get("oaapi") == null ? "" : fieldObj.get("oaapi").toString();
            String filedtype = fieldObj.get("filedtype") == null ? "" : fieldObj.get("filedtype").toString();//字段类型
            String subtableapi = fieldObj.get("subtableapi") == null ? "" : fieldObj.get("subtableapi").toString();//关联表API
            String subfileapi = fieldObj.get("subfileapi") == null ? "" : fieldObj.get("subfileapi").toString();//关联表OAID字段API
            if (StringUtils.isBlank(oaapi)) {
                return;
            }
            if (!filedtype.equals("当天")) {//字段类型为【当天】时，默认值为当前日期，无需过虑空值字段
                if (v == null || "null".equals(v.toString()) || StringUtils.isBlank(v.toString())) {
                    return;
                }
            }
            JSONObject obj = new JSONObject();
            obj.put("fieldName", oaapi);
            if (filedtype.equals("文件")) {
                JSONArray fieldValue = new JSONArray();
                JSONArray v_jarr = JSONArray.fromObject(v);
                for (Object v_obj : v_jarr) {
                    JSONObject fileobj = new JSONObject();
                    JSONObject v_json = JSONObject.fromObject(v_obj);
                    String fileid = v_json.get("fileid") == null ? "" : v_json.get("fileid").toString();
                    String filePath = fileUrl + "api/getFileUrl?id=" + fileid;
                    String fileName = v_json.get("filename") == null ? "" : v_json.get("filename").toString();
                    fileobj.put("filePath", filePath);
                    fileobj.put("fileName", fileName);
                    fieldValue.add(fileobj);
                }
                obj.put("fieldValue", fieldValue);
            } else if (filedtype.equals("用户")) {
                String oa_user_id = "";
                List<CCObject> userList = cs.cquery("ccuser", "id='" + v + "'");
                if (userList.size() > 0) {
                    CCObject userObj = userList.get(0);
                    String loginname = userObj.get("loginname") == null ? "" : userObj.get("loginname").toString();//用户名（员工编号）
                    List<CCObject> oauserList = cs.cquery("oayg", "ygbh like'" + loginname + "%' and accounttype='"+oa_user_type+"'");//OA员工
                    if (oauserList.size() > 0) {
                        CCObject oauserObj = oauserList.get(0);
                        oa_user_id = oauserObj.get("oaid") == null ? "" : oauserObj.get("oaid").toString();//人员ID
                    }
                }
                obj.put("fieldValue", oa_user_id);
            } else if (filedtype.equals("查找")) {
                String oa_filed_id = "";
                if (!StringUtils.isBlank(subtableapi) && !StringUtils.isBlank(subfileapi)) {
                    List<CCObject> subList = cs.cquery(subtableapi, "id='" + v + "'");
                    if (subList.size() > 0) {
                        CCObject subObj = subList.get(0);
                        oa_filed_id = subObj.get(subfileapi) == null ? "" : subObj.get(subfileapi).toString();//人员ID
                    }
                }
                obj.put("fieldValue", oa_filed_id);
            } else if (filedtype.equals("查找多选")) {
                List<Object> vList = Lists.newArrayList();
                Arrays.asList(v.toString().split(";")).forEach(key -> {
                    List<CCObject> subList = cs.cquery(subtableapi, "id='" + key + "'");
                    if (subList.size() > 0) {
                        CCObject subObj = subList.get(0);
                        String oa_filed_id = subObj.get(subfileapi) == null ? "" : subObj.get(subfileapi).toString();//人员ID
                        vList.add(oa_filed_id);
                    }
                });
                if (CollectionUtils.isNotEmpty(vList)) {
                    obj.put("fieldValue", StringUtils.join(vList, ","));
                }
            } else if (filedtype.equals("选项列表转换")) {
                Map<String, String> dict = dictMap.get(k);
                if (MapUtils.isNotEmpty(dict)) {
                    List<Object> vList = Lists.newArrayList();
                    Arrays.asList(v.toString().split(";")).forEach(key -> {
                        if (dict.containsKey(key)) {
                            vList.add(dict.get(key));
                        }
                    });
                    if (CollectionUtils.isNotEmpty(vList)) {
                        obj.put("fieldValue", StringUtils.join(vList, ","));
                    }
                }
            } else if (filedtype.equals("百分比")) {//除以100
                BigDecimal v_new = new BigDecimal(v.toString()).divide(new BigDecimal(100));
                obj.put("fieldValue", v_new.toString());
            } else if (filedtype.equals("万元")) {//乘以10000
                BigDecimal v_new = new BigDecimal(v.toString()).multiply(new BigDecimal(10000));
                obj.put("fieldValue", v_new.toString());
            } else if (filedtype.equals("当天")) {//乘以10000
                Date nowDate = new Date(); // 当前日期Date
                String currentTime = sdf.format(nowDate);
                obj.put("fieldValue", currentTime);
            } else {
                obj.put("fieldValue", v);
            }
            list.add(obj);
        });
        return list;
    }

    /**
     * 子表映射(CRM-->OA)
     *
     * @param objectApiName crm对象api
     * @param recordID      crm主表记录id
     * @param fieldApi      crm子表关联主表字段
     * @param modelName     oa映射表模块名称
     * @return
     */
    public List<JSONObject> dealOASubParam(String objectApiName, String recordID, String fieldApi, String modelName,String oa_user_type) {
        CCService cs = new CCService(userInfo);
        List<CCObject> subObj = cs.cquery(objectApiName, fieldApi + "='" + recordID + "'");//子表
        if (CollectionUtils.isEmpty(subObj)) {
            log.info("无数据subObj，后续无需处理");
            return null;
        }
        log.info("subObj:{}====={}", subObj.size(), subObj);
        List<CCObject> oamappingObj = cs.cquery("oafieldmapping", "name='" + modelName + "'");//OA字段映射;
        if (CollectionUtils.isEmpty(oamappingObj)) {
            log.info("无数据oamappingObj，后续无需处理");
            return null;
        }
        log.info("================");
        log.info("oamappingObj:=={}==={}", oamappingObj.size(), oamappingObj);
        Map<String, CCObject> fieldMap = Maps.newHashMap();
        oamappingObj.forEach(d -> {
            String key = d.get("crmapi") == null ? "" : d.get("crmapi").toString();
            if (StringUtils.isBlank(key)) {
                return;
            }
            fieldMap.put(key, d);
        });
        List<JSONObject> result = Lists.newArrayList();
//        int num = 0;//子表序号
        for (CCObject d : subObj) {
            JSONObject one = new JSONObject();
            List<JSONObject> list = Lists.newArrayList();
            d.forEach((k, v) -> {
                //k 字段名-->fieldMap.key v 字段值
                CCObject fieldObj = fieldMap.get(k);
                if (fieldObj == null) {
                    return;
                }
                String oaapi = fieldObj.get("oaapi") == null ? "" : fieldObj.get("oaapi").toString();
                String filedtype = fieldObj.get("filedtype") == null ? "" : fieldObj.get("filedtype").toString();
                String subtableapi = fieldObj.get("subtableapi") == null ? "" : fieldObj.get("subtableapi").toString();//关联表API
                String subfileapi = fieldObj.get("subfileapi") == null ? "" : fieldObj.get("subfileapi").toString();//关联表OAID字段API
                if (StringUtils.isBlank(oaapi)) {
                    return;
                }
                if (!filedtype.equals("当天")) {//字段类型为【当天】时，默认值为当前日期，无需过虑空值字段
                    if (v == null || "null".equals(v.toString()) || StringUtils.isBlank(v.toString())) {
                        return;
                    }
                }
                JSONObject obj = new JSONObject();
                obj.put("fieldName", oaapi);
                if (filedtype.equals("文件")) {
                    //查文件
//                    obj.put("filePath", "filePath");
//                    obj.put("fileName", "fileName");
                } else if (filedtype.equals("用户")) {
                    String oa_user_id = "";
                    List<CCObject> userList = cs.cquery("ccuser", "id='" + v + "'");
                    if (userList.size() > 0) {
                        CCObject userObj = userList.get(0);
                        String loginname = userObj.get("loginname") == null ? "" : userObj.get("loginname").toString();//用户名（员工编号）
                        List<CCObject> oauserList = cs.cquery("oayg", "ygbh like'" + loginname + "%' and accounttype='"+oa_user_type+"'");//OA员工
                        if (oauserList.size() > 0) {
                            CCObject oauserObj = oauserList.get(0);
                            oa_user_id = oauserObj.get("oaid") == null ? "" : oauserObj.get("oaid").toString();//人员ID
                        }
                    }
                    obj.put("fieldValue", oa_user_id);
                } else if (filedtype.equals("查找")) {
                    String oa_filed_id = "";
                    if (!StringUtils.isBlank(subtableapi) && !StringUtils.isBlank(subfileapi)) {
                        List<CCObject> subList = cs.cquery(subtableapi, "id='" + v + "'");
                        if (subList.size() > 0) {
                            CCObject sub_Obj = subList.get(0);
                            oa_filed_id = sub_Obj.get(subfileapi) == null ? "" : sub_Obj.get(subfileapi).toString();//人员ID
                        }
                    }
                    obj.put("fieldValue", oa_filed_id);
                } else if (filedtype.equals("查找多选拆分")) {
                    List<Object> vList = Lists.newArrayList();
                    Arrays.asList(v.toString().split(";")).forEach(key -> {
                        List<CCObject> subList = cs.cquery(subtableapi, "id='" + key + "'");
                        if (subList.size() > 0) {
                            CCObject sub_Obj = subList.get(0);
                            String oa_filed_id = sub_Obj.get(subfileapi) == null ? "" : sub_Obj.get(subfileapi).toString();//人员ID
                            vList.add(oa_filed_id);
                        }
                    });
                    if (CollectionUtils.isNotEmpty(vList)) {
                        obj.put("fieldValue", StringUtils.join(vList, ","));
                    }
                } else if (filedtype.equals("选项列表转换")) {
                    Map<String, String> dict = dictMap.get(k);
                    if (MapUtils.isNotEmpty(dict)) {
                        List<Object> vList = Lists.newArrayList();
                        Arrays.asList(v.toString().split(";")).forEach(key -> {
                            if (dict.containsKey(key)) {
                                vList.add(dict.get(key));
                            }
                        });
                        if (CollectionUtils.isNotEmpty(vList)) {
                            obj.put("fieldValue", StringUtils.join(vList, ","));
                        }
                    }
                } else if (filedtype.equals("百分比")) {//除以100
                    BigDecimal v_new = new BigDecimal(v.toString()).divide(new BigDecimal(100));
                    obj.put("fieldValue", v_new.toString());
                } else if (filedtype.equals("万元")) {//乘以10000
                    BigDecimal v_new = new BigDecimal(v.toString()).multiply(new BigDecimal(10000));
                    obj.put("fieldValue", v_new.toString());
                } else if (filedtype.equals("当天")) {//乘以10000
                    Date nowDate = new Date(); // 当前日期Date
                    String currentTime = sdf.format(nowDate);
                    obj.put("fieldValue", currentTime);
                } else {
                    obj.put("fieldValue", v);
                }
                list.add(obj);
            });
            if (CollectionUtils.isNotEmpty(list)) {
                one.put("workflowRequestTableFields", list);
                one.put("recordOrder", "0");
                result.add(one);
            }
        }
        return result;
    }

    /**
     * 子表映射2（合同查找多选拆分成多个子表）(CRM-->OA)
     *
     * @param objectApiName crm对象api
     * @param recordID      crm主表记录id
     * @param fieldApi      crm子表关联主表字段
     * @param modelName     oa映射表模块名称
     * @return
     */
    public List<JSONObject> dealOAhtSubParam(String objectApiName, String recordID, String fieldApi, String modelName) {
        CCService cs = new CCService(userInfo);
        List<CCObject> subObj = cs.cquery(objectApiName, fieldApi + "='" + recordID + "'");//子表
        if (CollectionUtils.isEmpty(subObj)) {
            log.info("无数据subObj，后续无需处理");
            return null;
        }
        log.info("subObj:{}====={}", subObj.size(), subObj);
        List<CCObject> oamappingObj = cs.cquery("oafieldmapping", "name='" + modelName + "'");//OA字段映射;
        if (CollectionUtils.isEmpty(oamappingObj)) {
            log.info("无数据oamappingObj，后续无需处理");
            return null;
        }
        log.info("================");
        log.info("oamappingObj:=={}==={}", oamappingObj.size(), oamappingObj);
        Map<String, CCObject> fieldMap = Maps.newHashMap();
        oamappingObj.forEach(d -> {
            String key = d.get("crmapi") == null ? "" : d.get("crmapi").toString();
            if (StringUtils.isBlank(key)) {
                return;
            }
            fieldMap.put(key, d);
        });
        List<JSONObject> result = Lists.newArrayList();
//        int num = 0;//子表序号
        for (CCObject d : subObj) {
            d.forEach((k, v) -> {
                //k 字段名-->fieldMap.key v 字段值
                CCObject fieldObj = fieldMap.get(k);
                if (fieldObj == null) {
                    return;
                }
                String oaapi = fieldObj.get("oaapi") == null ? "" : fieldObj.get("oaapi").toString();
                String filedtype = fieldObj.get("filedtype") == null ? "" : fieldObj.get("filedtype").toString();
                String subtableapi = fieldObj.get("subtableapi") == null ? "" : fieldObj.get("subtableapi").toString();//关联表API
                String subfileapi = fieldObj.get("subfileapi") == null ? "" : fieldObj.get("subfileapi").toString();//关联表OAID字段API
                if (StringUtils.isBlank(oaapi)) {
                    return;
                }
                if (!filedtype.equals("当天")) {//字段类型为【当天】时，默认值为当前日期，无需过虑空值字段
                    if (v == null || "null".equals(v.toString()) || StringUtils.isBlank(v.toString())) {
                        return;
                    }
                }
                if (filedtype.equals("查找多选拆分")) {
                    Arrays.asList(v.toString().split(";")).forEach(key -> {
                        JSONObject one = new JSONObject();
                        List<JSONObject> list = Lists.newArrayList();
                        JSONObject obj = new JSONObject();
                        obj.put("fieldName", oaapi);
                        List<CCObject> subList = cs.cquery(subtableapi, "id='" + key + "'");
                        if (subList.size() > 0) {
                            CCObject sub_Obj = subList.get(0);
                            String oa_filed_id = sub_Obj.get(subfileapi) == null ? "" : sub_Obj.get(subfileapi).toString();//人员ID
                            obj.put("fieldValue", oa_filed_id);
                        }
                        list.add(obj);
                        if (CollectionUtils.isNotEmpty(list)) {
                            one.put("workflowRequestTableFields", list);
                            one.put("recordOrder", "0");
                            result.add(one);
                        }
                    });
                }
            });
        }
        return result;
    }

    /**
     * 主表映射(OA-->CRM)
     *
     * @param objectApiName crm对象api
     * @param object       data主表数据
     * @param modelName     oa映射表模块名称
     * @return
     */
    public List<JSONObject> dealCRMMainParam(String objectApiName, JSONObject object, String modelName) {
        CCService cs = new CCService(userInfo);
        List<CCObject> oamappingObj = cs.cquery("oafieldmapping", "name='" + modelName + "'");//OA字段映射;
        if (CollectionUtils.isEmpty(oamappingObj)) {
            log.info("无数据oamappingObj，后续无需处理");
            return null;
        }
        log.info("================");
        log.info("oamappingObj:=={}==={}", oamappingObj.size(), oamappingObj);
        Map<String, CCObject> fieldMap = Maps.newHashMap();
        oamappingObj.forEach(d -> {
            String key = d.get("crmapi") == null ? "" : d.get("crmapi").toString();
            if (StringUtils.isBlank(key)) {
                return;
            }
            fieldMap.put(key, d);
        });
        List<JSONObject> list = Lists.newArrayList();
        object.forEach((k, v) -> {//k 字段名-->fieldMap.key v 字段值
            CCObject fieldObj = fieldMap.get(k);
            if (fieldObj == null) {
                return;
            }
            String oaapi = fieldObj.get("oaapi") == null ? "" : fieldObj.get("oaapi").toString();
            String crmapi = fieldObj.get("crmapi") == null ? "" : fieldObj.get("crmapi").toString();
            if (StringUtils.isBlank(oaapi)) {
                return;
            }
            if (v == null || "null".equals(v.toString()) || StringUtils.isBlank(v.toString())) {
                return;
            }
            String filedtype = fieldObj.get("filedtype") == null ? "" : fieldObj.get("filedtype").toString();//字段类型
            String subtableapi = fieldObj.get("subtableapi") == null ? "" : fieldObj.get("subtableapi").toString();//关联表API
            String subfileapi = fieldObj.get("subfileapi") == null ? "" : fieldObj.get("subfileapi").toString();//关联表OAID字段API
            if (filedtype.equals("文件")) {
                //推送文件CRMID，无需处理
            } else if (filedtype.equals("用户")) {
                //所有人字段不推送
            } else if (filedtype.equals("查找")) {
                String crm_id = "";
                if (!StringUtils.isBlank(subtableapi)&&!StringUtils.isBlank(subfileapi)){
                    List<CCObject>  subList = cs.cquery(subtableapi,subfileapi+"='"+v+"'");
                    if (subList.size()>0){
                        CCObject subObj = subList.get(0);
                        crm_id = subObj.get("id")==null?"":subObj.get("id").toString();//CRM记录ID
                    }
                }
                object.put(k,crm_id);
            } else if (filedtype.equals("选项列表转换")) {
                Map<String,String> dict = dictMap.get(k);
                if(MapUtils.isNotEmpty(dict)){
                    List<Object> vList = Lists.newArrayList();
                    Arrays.asList(v.toString().split(",")).forEach(key->{
                        dict.forEach((crmk,oav) ->{
                            if (oav.toString().equals(key)){
                                vList.add(crmk);
                            }
                        });
                    });
                    if(CollectionUtils.isNotEmpty(vList)){
                        object.put(k,StringUtils.join(vList,";"));
                    }
                }
            } else if (filedtype.equals("百分比")) {//乘以100
                BigDecimal v_new = new BigDecimal(v.toString()).multiply(new BigDecimal(100));
                object.put(k,v_new.toString());
            } else if (filedtype.equals("万元")) {//除以10000
                BigDecimal v_new = new BigDecimal(v.toString()).divide(new BigDecimal(10000));
                object.put(k,v_new.toString());
            }
        });
        list.add(object);
        return list;
    }
    /**
     * 子表映射(OA-->CRM)
     * @param objectArr       data子表数据
     * @param modelName     oa映射表模块名称
     * @return
     */
    public List<JSONObject> dealCRMSubParam(JSONArray objectArr, String modelName) {
        CCService cs = new CCService(userInfo);
        List<JSONObject> list = Lists.newArrayList();
        List<CCObject> oamappingObj = cs.cquery("oafieldmapping", "name='" + modelName + "'");//OA字段映射;
        if (CollectionUtils.isEmpty(oamappingObj)) {
            log.info("无数据oamappingObj，后续无需处理");
            return null;
        }
        log.info("================");
        log.info("oamappingObj:=={}==={}", oamappingObj.size(), oamappingObj);
        Map<String, CCObject> fieldMap = Maps.newHashMap();
        oamappingObj.forEach(d -> {
            String key = d.get("crmapi") == null ? "" : d.get("crmapi").toString();
            if (StringUtils.isBlank(key)) {
                return;
            }
            fieldMap.put(key, d);
        });
        for (Object d : objectArr) {
            JSONObject object = JSONObject.fromObject(d);
            object.forEach((k, v) -> {//k 字段名-->fieldMap.key v 字段值
                CCObject fieldObj = fieldMap.get(k);
                if (fieldObj == null) {
                    return;
                }
                String oaapi = fieldObj.get("oaapi") == null ? "" : fieldObj.get("oaapi").toString();
                String crmapi = fieldObj.get("crmapi") == null ? "" : fieldObj.get("crmapi").toString();
                if (StringUtils.isBlank(oaapi)) {
                    return;
                }
                if (v == null || "null".equals(v.toString()) || StringUtils.isBlank(v.toString())) {
                    return;
                }
                String filedtype = fieldObj.get("filedtype") == null ? "" : fieldObj.get("filedtype").toString();//字段类型
                String subtableapi = fieldObj.get("subtableapi") == null ? "" : fieldObj.get("subtableapi").toString();//关联表API
                String subfileapi = fieldObj.get("subfileapi") == null ? "" : fieldObj.get("subfileapi").toString();//关联表OAID字段API
                if (filedtype.equals("文件")) {
                    //推送文件CRMID，无需处理
                } else if (filedtype.equals("用户")) {
                    //所有人字段不推送
                } else if (filedtype.equals("查找")) {
                    String crm_id = "";
                    if (!StringUtils.isBlank(subtableapi)&&!StringUtils.isBlank(subfileapi)){
                        List<CCObject>  subList = cs.cquery(subtableapi,subfileapi+"='"+v+"'");
                        if (subList.size()>0){
                            CCObject subObj = subList.get(0);
                            crm_id = subObj.get("id")==null?"":subObj.get("id").toString();//CRM记录ID
                        }
                    }
                    object.put(k,crm_id);
                } else if (filedtype.equals("选项列表转换")) {
                    Map<String,String> dict = dictMap.get(k);
                    if(MapUtils.isNotEmpty(dict)){
                        List<Object> vList = Lists.newArrayList();
                        Arrays.asList(v.toString().split(",")).forEach(key->{
                            dict.forEach((crmk,oav) ->{
                                if (oav.toString().equals(key)){
                                    vList.add(crmk);
                                }
                            });
                        });
                        if(CollectionUtils.isNotEmpty(vList)){
                            object.put(k,StringUtils.join(vList,";"));
                        }
                    }
                } else if (filedtype.equals("百分比")) {//乘以100
                    BigDecimal v_new = new BigDecimal(v.toString()).multiply(new BigDecimal(100));
                    object.put(k,v_new.toString());
                } else if (filedtype.equals("万元")) {//除以10000
                    BigDecimal v_new = new BigDecimal(v.toString()).divide(new BigDecimal(10000));
                    object.put(k,v_new.toString());
                }
            });
            list.add(object);
        }
        return list;
    }

}
